from urllib import request,parse
import ssl
import random
import json

ua_list = [
	'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
	'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0',
	'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
	'Mozilla/5.0 (Windows; U; Windows NT 6.1; ) AppleWebKit/534.12 (KHTML, like Gecko) Maxthon/3.0 Safari/534.12',
	'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E)',
	'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.41 Safari/535.1 QQBrowser/6.9.11079.201'
]

# 加载一个页面
def loadPage(url,fanyi="hello"):
	userAgent = random.choice(ua_list)
	headers = {
		'User-Agent':userAgent
	}
	data = {
		"i": fanyi,
		"from": "AUTO",
		"to": "AUTO",
		"smartresult": "dict",
		"client": "fanyideskweb",
		"salt": "15680856530661",
		"sign": "5a2be1c20ec365b21303536f22f2aebc",
		"ts": "1568085653066",
		"bv": "dbbd037970d0424cdfdc91fa162c9f40",
		"doctype": "json",
		"version": "2.1",
		"keyfrom": "fanyi.web",
		"action": "FY_BY_REALTlME"
    }
	data = parse.urlencode(data).encode("utf-8")
	context = ssl._create_unverified_context()
	# 发起请求
	req = request.Request(url,headers = headers)
	#print(req) # <urllib.request.Request object at 0x00000000022D8710>

	# 打开响应的对象
	response = request.urlopen(req,data = data)
	#print(response) # <http.client.HTTPResponse object at 0x0000000002A236A0>

	# 获取响应的内容
	html = response.read()
	
	# 对网页进行解码
	content = html.decode('utf-8')
	
	return content
def toJson(fanyi):
	url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
	content = loadPage(url,fanyi)
	json_con = json.loads(content)
	json_ret = json_con["translateResult"][0]
	print(json_ret[0]["tgt"])



from urllib import parse
if __name__ == '__main__':
	key = "0"
	while key == "0":
		fanyi = input('请输入要翻译的内容: ')
		toJson(fanyi )
		key = input("输入0继续: ")
